//
// Created by Administrator on 2021/10/21.
//

#include "ShaderUtil.h"

static std::map<std::string, Shader*> shaderCacheMap;

/**
 * 编译所有shader
 */
void ShaderUtil::initShaders() {
    log_info("initShaders");

    for (String shaderName : Config::SHADER_NAME_ARRAY) {
        log_info("compile shader: %s", shaderName.c_str());

        String vsPath = Config::SHADER_FOLDER +  shaderName + ".vs";
        String fsPath = Config::SHADER_FOLDER +  shaderName + ".fs";
        Shader * shader = new Shader(shaderName, vsPath, fsPath);
        MAssert::check(shader->check(), "shader不可用");
        shaderCacheMap.insert(std::make_pair(shaderName.c_str(), shader));
    }
}

/**
 * 根据shader名称查找shader
 * @param name 名称
 * @return shader
 */
Shader* ShaderUtil::getShaderByName(String _name) {
    const char* name = _name.c_str();
    if(shaderCacheMap.empty()){
        initShaders();
    }
    if(shaderCacheMap.count(name) > 0){
        return shaderCacheMap[name];
    }
    MAssert::check(false, "shader不可用");
    return NULL;
}

/**
 * 释放所有shaders
 */
void ShaderUtil::releaseShaders() {
    if(!shaderCacheMap.empty()) {
        for (auto iter = shaderCacheMap.begin(); iter != shaderCacheMap.end(); iter++) {
            auto second = iter->second;
            if (second) {
                // 释放指针
                SAFE_DELETE(iter->second);
            }
        }
    }
    std::map<std::string, Shader*>().swap(shaderCacheMap);
}
